/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.dialect.page;

import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.scripting.xmltags.TextSqlNode;

import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 分页节点limit实现
 * 
 * @author jianggujin
 *
 */
public class JOraclePageSqlNode extends JAbstractPageSqlNode {

    private final StaticTextSqlNode openSqlNode;
    private final TextSqlNode closeSqlNode;

    public JOraclePageSqlNode(MixedSqlNode mixedSqlNode, String name, String startRow, String endRow, String pageSize) {
        super(mixedSqlNode, name, startRow, endRow, pageSize);
        openSqlNode = new StaticTextSqlNode("SELECT * FROM (  SELECT TMP_PAGE.*, ROWNUM ROW_ID FROM ( ");
        // 指定参数名称
        String sql = null;
        if (!dynamicParse) {
            sql = JStringUtils.format(" ) TMP_PAGE) WHERE ROW_ID <= #{{}.{}} AND ROW_ID > #{{}.{}}", this.name,
                    this.endRow, this.name, this.startRow);
        } else {
            sql = JStringUtils.format(" ) TMP_PAGE) WHERE ROW_ID <= #{{}} AND ROW_ID > #{{}}", DYNAMIC_END_ROW_KEY,
                    DYNAMIC_START_ROW_KEY);
        }
        this.closeSqlNode = new TextSqlNode(sql);
    }

    @Override
    protected void applyNode(DynamicContext context) {
        openSqlNode.apply(context);
        super.applyNode(context);
        closeSqlNode.apply(context);
    }
}